package com.zhentao.equipment.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.equipment.mapper.DeviceInfoMapper;
import com.zhentao.pojo.DeviceInfo;
import com.zhentao.util.ResultVo;
import com.zhentao.util.exception.ApiException;
import com.zhentao.util.Enum.ApiServiceExceptionEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


import java.util.Date;

@Service
public class DeviceService {

    @Autowired
    private DeviceInfoMapper deviceInfoMapper;

    public ResultVo add(DeviceInfo req) {
        if (!StringUtils.hasText(req.getDeviceCode())) {
            throw new ApiException(ApiServiceExceptionEnum.RESULT_ERROR.getCode(), "设备编码不能为空");
        }
        Long exists = deviceInfoMapper.selectCount(new LambdaQueryWrapper<DeviceInfo>()
                .eq(DeviceInfo::getDeviceCode, req.getDeviceCode()));
        if (exists != null && exists > 0) {
            throw new ApiException(ApiServiceExceptionEnum.RESULT_ERROR.getCode(), "设备编码已存在");
        }
        req.setCreateTime(new Date());
        req.setUpdateTime(new Date());
        deviceInfoMapper.insert(req);
        return ResultVo.success();
    }

    public ResultVo update(DeviceInfo req) {
        if (req.getDeviceId() == null) {
            throw new ApiException(ApiServiceExceptionEnum.RESULT_ERROR.getCode(), "设备ID不能为空");
        }
        req.setUpdateTime(new Date());
        deviceInfoMapper.updateById(req);
        return ResultVo.success();
    }

    public ResultVo delete(Long id) {
        deviceInfoMapper.deleteById(id);
        return ResultVo.success();
    }

    public ResultVo detail(Long id) {
        return ResultVo.success(deviceInfoMapper.selectById(id));
    }

    public ResultVo page(Integer pageNum, Integer pageSize, String deviceType, Integer status, String keyword) {
        Page<DeviceInfo> page = new Page<>(pageNum == null ? 1 : pageNum, pageSize == null ? 10 : pageSize);
        LambdaQueryWrapper<DeviceInfo> qw = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(deviceType)) {
            qw.eq(DeviceInfo::getDeviceType, deviceType);
        }
        if (status != null) {
            qw.eq(DeviceInfo::getStatus, status);
        }
        if (StringUtils.hasText(keyword)) {
            qw.like(DeviceInfo::getDeviceName, keyword).or().like(DeviceInfo::getDeviceCode, keyword);
        }
        qw.orderByDesc(DeviceInfo::getUpdateTime);
        return ResultVo.success(deviceInfoMapper.selectPage(page, qw));
    }
}




